package com.itheima.controller;

import com.itheima.Service.OrderSettingService;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.pojo.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 模版下载
     * @param filename
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filename) {
        try {
            // 1. 基础路径配置（建议抽取到 @Value 或配置类）
            String baseDir = "E:/chuanzhi/bxg-health-backend/src/main/resources/templates/";
            Path basePath = Paths.get(baseDir).toRealPath();
            Path filePath = basePath.resolve(filename).normalize();

            // 2. 校验路径合法性
            if (!filePath.startsWith(basePath)) {
                return ResponseEntity.badRequest().build();
            }

            // 3. 加载资源并检查存在性
            Resource resource = new FileSystemResource(filePath);
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 4. 设置响应头
            HttpHeaders headers = new HttpHeaders();
            ContentDisposition contentDisposition = ContentDisposition.attachment()
                    .filename(resource.getFilename(), StandardCharsets.UTF_8)
                    .build();
            headers.setContentDisposition(contentDisposition);

            // 5. 动态设置 Content-Type
            String contentType = Files.probeContentType(filePath);
            headers.setContentType(MediaType.parseMediaType(
                    Optional.ofNullable(contentType).orElse("application/octet-stream")
            ));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting){
        try {
            log.info("根据日期修改可预约人数：{}",orderSetting);
            orderSettingService.editNumberByOrderDate(orderSetting);
        }catch (Exception e){
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
    }

    /**
     * 根据年月查询对应的预约设置信息
     * @param month
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month){
        try{
            log.info("根据年月查询对应的预约设置信息：{}",month);
           List<OrderSetting> orderSettings = orderSettingService.getOrderSettingByMonth(month);
            // 创建返回结果列表
            List<Map<String, Object>> result = new ArrayList<>();
            for (OrderSetting orderSetting : orderSettings) {
                Map<String, Object> map = new HashMap<>();
                map.put("date", orderSetting.getOrderDate().getDate()); // 获取日期的天数
                map.put("number", orderSetting.getNumber());
                map.put("reservations", orderSetting.getReservations());
                result.add(map);
            }
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS,result);
        }catch (Exception e){
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }

    /**
     * Excel文件上传，并解析文件内容保存到数据库
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile){
        try {
            //读取Excel文件数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            if(list != null && list.size() > 0){
                List<OrderSetting> orderSettingList = new ArrayList<>();
                for (String[] strings : list) {
                    OrderSetting orderSetting =
                            new OrderSetting(new Date(strings[0]), Integer.parseInt(strings[1]));
                    orderSettingList.add(orderSetting);
                }
                orderSettingService.add(orderSettingList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }
}
